// components/tabbar/tabbar.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
var request = require("../../utils/request.js");


Component({
  options: {
    addGlobalClass: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    showTabbar: {
      type: Boolean,
      value: true
    },
    tabNavIndex: {
      type: Number,
      value: 0
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    token: ''
  },
  ready() {
    this.setData({
      token: wx.getStorageSync('token')
    })
  },
  /**
   * 组件的方法列表
   */
  methods: {
    toPage(e) {
      if (this.data.tabNavIndex == e.currentTarget.dataset.index) {
        return
      }
      wx.redirectTo({
        url: e.currentTarget.dataset.path,
      })
    },
    //授权
    bindGetUserInfo: function (e) {
      let url = e.currentTarget.dataset.path
      let that = this;
      let userInfo = e.detail.userInfo;
      wx.setStorageSync('userInfo', userInfo)
      that.setData({
        userInfo: userInfo
      })
      if (userInfo) {
        wx.login({
          success: res => {
            that.getToken(res.code, url);
          }
        });
      }
    },
    /**
   * 获取Token
   * @param {String} code 微信返回的用户code
   */
    getToken(code, path) {
      let that = this
      let info = this.data.userInfo;
      let url = '/customer/info/authorize'
      let params = {
        avatar: info.avatarUrl,
        code: code,
        nickname: info.nickName,
        sex: info.gender == 0 ? 'UNKNOWN' : info.gender == 1 ? 'MEN' : 'WOMEN',
      }
      request.http(url, 'POST', params)
        .then(res => {
          var data = res.data
          if (data.code == 200) {
            let token = data.data.token
            wx.setStorageSync('token', token)
            wx.setStorageSync('customerId', data.data.customerId)
            that.setData({
              token
            })
            wx.redirectTo({
              url: path
            })
            //判断是不是新用户，新用户授权后跳转 绑定车牌页面
            if(data.data.isNew == 1){
              wx.navigateTo({ url: '../licencePlate/licencePlate' }) 
            }
          }
        })
    },
  }
})